﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model.Base
{
    public static class NewModelBase
    {
        //数据转换
        public static T RowToModel<T>(this DataRow dr)
        {
            Type t = typeof(T);
            object rs = t.Assembly.CreateInstance(t.Namespace + "." + t.Name);
            foreach (var item in t.GetProperties())
            {
                if (dr.Table.Columns.Contains(item.Name))
                {
                    object val = ConvertRow(item.PropertyType.Name, dr[item.Name]);
                    item.SetValue(rs, val, null);
                }
            }
            return (T)rs;
        }

        public static List<T> TableToModel<T>(this DataTable dt)
        {
            List<T> rs = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                rs.Add(dr.RowToModel<T>());
            }
            return rs;
        }
        //类型转换
        public static object ConvertRow(string t, object obj)
        {
            object rs = null;
            switch (t)
            {
                case "Int32":
                    if (obj != null && obj.ToString() != "")
                    {
                        rs = Convert.ToInt32(obj.ToString());
                    }
                    else
                    {
                        rs = null;
                    }
                    break;
                case "Double":
                    if (obj != null && obj.ToString() != "")
                    {
                        rs = Convert.ToDouble(obj.ToString());
                    }
                    else
                    {
                        rs = null;
                    }
                    break;
                case "Decimal":
                    if (obj != null && obj.ToString() != "")
                    {
                        rs = Convert.ToDecimal(obj.ToString());
                    }
                    else
                    {
                        rs = null;
                    }
                    break;
                case "DateTime":
                    if (obj != null && obj.ToString() != "")
                    {
                        rs = Convert.ToDateTime(obj.ToString());
                    }
                    else
                    {
                        rs = null;
                    }

                    break;
                case "String":
                default:
                    rs = obj.ToString();
                    break;
            }
            return rs;
        }
    }
}
